﻿using Kylin.Wiki.Core.Configuration;
using Kylin.Wiki.Model.Api;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Kylin.Wiki.Web.Controllers.System
{
    [Route("api/[controller]")]
    [ApiController]
    public class UploadController : ControllerBase
    {
        [HttpPost]
        public ApiResult<object> Upload([FromServices] IWebHostEnvironment environment)
        {
            var files = Request.Form.Files[0];
            if (files == null)
                return new ApiResult<object>(false, Core.Enum.HttpStateCode.Error, "请上传文件"); 
            if (files.Length > AppSetting.LimitUpFileSizee * 1024 * 1024)
            {
                return new ApiResult<object>(false, Core.Enum.HttpStateCode.Error, $"文件大小不能超过：{ AppSetting.LimitUpFileSizee}M");
            }
            string filePath = $"Images/{DateTime.Now.ToString("yyyMMddHHmmsss") + new Random().Next(1000, 9999)}/";
            string fullPath = Path.Combine(environment.WebRootPath, filePath);
            int i = 0;
            //   List<string> fileNames = new List<string>();
            try
            {
                if (!Directory.Exists(fullPath))
                    Directory.CreateDirectory(fullPath);
                string fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(files.FileName);
                //if (fileNames.Contains(fileName))
                //{
                //    fileName += $"({i}){fileName}";
                //}
                //fileNames.Add(fileName);
                using (var stream = new FileStream(fullPath+ fileName, FileMode.Create))
                {
                    files.CopyTo(stream);
                }
                filePath = Path.Combine(filePath, fileName);

            }
            catch (Exception ex)
            {
                //Logger.Error($"上传文件失败：{typeof(T).GetEntityTableCnName()},路径：{filePath},失败文件:{files[i]},{ex.Message + ex.StackTrace}");
                return new ApiResult<object>(false, Core.Enum.HttpStateCode.Error, "文件上传失败");
            }
            return new ApiResult<object>
            {
                Code = Core.Enum.HttpStateCode.Success,
                Success = true,
                Data = filePath,
                Message = "上传成功"
            };
        }
    }
}
